package org.edu.modules.enroll.controller;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.tomcat.jni.User;
import org.edu.common.api.vo.Result;
import org.edu.modules.enroll.entity.*;
import org.edu.modules.enroll.service.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 学号编制
 * @author yhx
 */
@Api(tags = "学号编制")
@RestController
@RequestMapping("enroll/createNum")
public class CreateNumController {

    @Resource
    private VeBaseXhruleService veBaseXhruleService;

    @Resource
    private VeZsRegistrationService veZsRegistrationService;

    @Resource
    private VeBaseSpecialtyService veBaseSpecialtyService;

    @Resource
    private VeBaseBanjiService veBaseBanjiService;

    @Resource
    private VeBaseStudentService veBaseStudentService;

    @Resource
    private VeDictYearsService veDictYearsService;
    @Resource
    private IVeBaseManageService iVeBaseManageService;
    @ApiOperation("批量编制学号")
    @PostMapping("/batchCreateNum")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> batchCreateNum(@ApiParam("ID字符串") @RequestParam("ids") String ids){

        //获取规则集合
        QueryWrapper<VeBaseXhrule> wrapper = new QueryWrapper<>();
        wrapper.eq("status",1);
        List<VeBaseXhrule> list = veBaseXhruleService.list(wrapper);

        System.out.println(list);

        //位数
        Integer yearDigit = null;
        Integer specDigit = null;
        Integer clazzDigit = null;
        Integer numDigit = null;

        //获取位数、排序
        for (int i = 0; i < list.size(); i++) {
            if(list.get(i).getId() == 1){
                yearDigit = list.get(i).getDigit();
            }else if(list.get(i).getId() == 2){
                specDigit = list.get(i).getDigit();
            }else if(list.get(i).getId() == 3){
                clazzDigit = list.get(i).getDigit();
            }else if(list.get(i).getId() == 4){
                numDigit = list.get(i).getDigit();
            }
        }

        //切割字符串，获取ID数组
        String[] split = ids.split(",");

        for (String s : split) {
            Long id = Long.parseLong(s);

            String year = "";
            String spec = "";
            String clazz = "";
            String num = "";

            //获取该ID的学生信息
            QueryWrapper<VeZsRegistration> qw = new QueryWrapper<>();
            qw.eq("id",id);
            VeZsRegistration one = veZsRegistrationService.getOne(qw);

            //专业ID
            Long specId = one.getSpecId();

            //年份规则
            if(yearDigit != null){
                //获取当前年份
                year = one.getRxnf();
                if(yearDigit == 2){
                    year = year.substring(2);
                }
            }

            //专业规则
            if(specDigit != null){
                //获取专业代码//2021.9.1
                QueryWrapper<VeBaseSpecialty> wrapperSpec = new QueryWrapper<>();
                wrapperSpec.eq("id",specId);
                spec = veBaseSpecialtyService.getOne(wrapperSpec).getZydm();
//                ---------------------------林彬辉
//                BasicResponseBO<VeBaseSpecialty> specialtyBo = iVeBaseManageService.getSpecialtyById(specId);
//                spec = specialtyBo.getResult().getZydm();//2022.2.18
//                ----------------------------
            }

            //班级规则
            if(clazzDigit != null){
                //根据班级ID获取班级代码
                Long clazzId = one.getClassId();
                QueryWrapper<VeBaseBanji> wrapperClazz = new QueryWrapper<>();//2021.9.1
                wrapperClazz.eq("id",clazzId);
                clazz = veBaseBanjiService.getOne(wrapperClazz).getXzbdm();
//                --------------------------林彬辉
//                BasicResponseBO<VeBaseBanji> listBasicResponseBO = iVeBaseManageService.getBanjiById(clazzId);
//                clazz = listBasicResponseBO.getResult().getXzbdm();//2022.2.18
//                -------------------------
            }

            //流水号规则
            if(numDigit != null){
                //条件构造器
                QueryWrapper<VeZsRegistration> wrapperReg = new QueryWrapper<>();
                wrapperReg.eq("specId",specId);
                wrapperReg.eq("isCheck",1);
                wrapperReg.eq("isAdmit",1);
                wrapperReg.eq("isReport",1);
                wrapperReg.eq("RXNF",one.getRxnf());
                wrapperReg.orderByAsc("create_time","id");
                List<VeZsRegistration> regList = veZsRegistrationService.list(wrapperReg);

                //获取流水号
                for (int i = 0; i < regList.size(); i++) {
                    if(regList.get(i).getId().equals(id)){
                        num = String.format("%0" + numDigit + "d", i+1);
                    }
                }
            }

            for (int i = 0; i < list.size(); i++) {
                //判断年份
                if(list.get(i).getId() == 1){
                    if(!(year.equals("") || year == null)){
                        list.get(i).setCode(year);
                    }
                }

                //判断专业
                if(list.get(i).getId() == 2){
                    if(!(spec.equals("") || spec == null)){
                        list.get(i).setCode(spec);
                    }
                }

                //判断班级
                if(list.get(i).getId() == 3){
                    if(!(clazz.equals("") || clazz == null)){
                        list.get(i).setCode(clazz);
                    }
                }

                //判断流水号
                if(list.get(i).getId() == 4){
                    if(!(num.equals("") || num == null)){
                        list.get(i).setCode(num);
                    }
                }
            }

            //排序
            Collections.sort(list, new Comparator<VeBaseXhrule>() {
                @Override
                public int compare(VeBaseXhrule o1, VeBaseXhrule o2) {
                    return o1.getListSort().compareTo(o2.getListSort());
                }
            });

            //拼接学号
            String stuNum = "";
            for (VeBaseXhrule veBaseXhrule : list) {
                stuNum += veBaseXhrule.getCode();
            }

            //将该学生信息写入学生表
//            VoStudentAndStudentInfo veBaseStudent = new VoStudentAndStudentInfo();
            VeBaseStudent veBaseStudent = new VeBaseStudent();
//            veBaseStudent.setId(one.getId());//林彬辉添加id
            veBaseStudent.setSfzh(one.getSfzh());
            veBaseStudent.setXh(stuNum);
            veBaseStudent.setXm(one.getXm());
            veBaseStudent.setXbm(one.getXbm());
//            veBaseStudent.setUserId("0");
            veBaseStudent.setMzm(one.getMzm());
            veBaseStudent.setBmh(one.getBmh());
            veBaseStudent.setJdfs(one.getJdfs());
            veBaseStudent.setXsdqztm("XS");

            //将入学年月转换成时间戳
            Date date = null;
            Long time = null;
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            try {
                date = formatter.parse(one.getRxny());
                time = date.getTime() / 1000;
            } catch (ParseException e) {
                e.printStackTrace();
            }

            veBaseStudent.setRxny(time);
            veBaseStudent.setXz(one.getXz());
            veBaseStudent.setFalId(one.getFalId());
            veBaseStudent.setSpecId(one.getSpecId());
            veBaseStudent.setBjId(one.getClassId());
            veBaseStudent.setGradeId(one.getGradeId());

            veBaseStudent.setCreateTime(System.currentTimeMillis()/1000);
            veBaseStudent.setUpdateTime(System.currentTimeMillis()/1000);

            veBaseStudent.setProvince(one.getProvince());
            veBaseStudent.setProvinceId(one.getProvinceId());
            veBaseStudent.setCity(one.getCity());
            veBaseStudent.setCityId(one.getCityId());
            veBaseStudent.setCounty(one.getCounty());
            veBaseStudent.setCountyId(one.getCountyId());
            veBaseStudent.setShengId(null);
            veBaseStudent.setShiId(null);
            veBaseStudent.setQuId(null);
            veBaseStudent.setSfkns(0);
            veBaseStudent.setTerminalId(0L);
            veBaseStudent.setZkzh(one.getZkzh());
            veBaseStudent.setKsh(one.getKsh());
            veBaseStudent.setUpdateStatus(0);

            //添加学生
//            veBaseStudentService.save(veBaseStudent);
//            林彬辉
            int res = veBaseStudentService.saveBaseStudent(veBaseStudent);
//            BasicResponseBO<Object> o = iVeBaseManageService.saveStudent(veBaseStudent);
//            if (o.getCode()==200){
            if (res>0){
                //修改编制学号标识
                UpdateWrapper<VeZsRegistration> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id",id);
                updateWrapper.set("isNum",1);
                veZsRegistrationService.update(updateWrapper);
            }else {
                return Result.OK("批量编制学号失败！");
            }


        }

        return Result.OK("批量编制学号成功！");
    }

    @ApiOperation(value="获取条件下 可编制学号的数量")
    @PostMapping(value = "/getCountBySearch")
    public Result<?> getCountBySearch(@ApiParam("班级ID") @RequestParam("clazzId") Long clazzId,
                                      @ApiParam("专业部ID") @RequestParam("facultyId") Long facultyId,
                                      @ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId){

        if(clazzId == 0){
            clazzId = null;
        }
        if(facultyId == 0){
            facultyId = null;
        }
        if(specialtyId == 0){
            specialtyId = null;
        }

        //条件构造器
        QueryWrapper<VeDictYears> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("curYear",1);
        VeDictYears one = veDictYearsService.getOne(queryWrapper);

        //获取当前年份
        String curYear = one.getCode();

        QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("classId");
        wrapper.eq("isCheck",1);
        wrapper.eq("isAdmit",1);
        wrapper.eq("isReport",1);
        wrapper.eq("isNum",0);
        wrapper.eq("RXNF",curYear);


        if(clazzId != null){
            wrapper.eq("classId",clazzId);
        }

        if(facultyId != null){
            wrapper.eq("falId",facultyId);
        }

        if(specialtyId != null){
            wrapper.eq("specId",specialtyId);
        }

        Integer count = veZsRegistrationService.count(wrapper);

        return Result.OK(count);
    }

    @ApiOperation(value="按条件批量编制学号")
    @PostMapping(value = "/batchCreateNumBySearch")
    public Result<?> batchReport(@ApiParam("班级ID") @RequestParam("clazzId") Long clazzId,
                                 @ApiParam("专业部ID") @RequestParam("facultyId") Long facultyId,
                                 @ApiParam("专业ID") @RequestParam("specialtyId") Long specialtyId){


        if(clazzId == 0){
            clazzId = null;
        }
        if(facultyId == 0){
            facultyId = null;
        }
        if(specialtyId == 0){
            specialtyId = null;
        }

        //条件构造器
        QueryWrapper<VeDictYears> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("curYear",1);
        VeDictYears one = veDictYearsService.getOne(queryWrapper);

        //获取当前年份
        String curYear = one.getCode();

        QueryWrapper<VeZsRegistration> wrapper = new QueryWrapper<>();

        wrapper.isNotNull("classId");
        wrapper.eq("isCheck",1);
        wrapper.eq("isAdmit",1);
        wrapper.eq("isReport",1);
        wrapper.eq("isNum",0);
        wrapper.eq("RXNF",curYear);

        if(clazzId != null){
            wrapper.eq("classId",clazzId);
        }

        if(facultyId != null){
            wrapper.eq("falId",facultyId);
        }

        if(specialtyId != null){
            wrapper.eq("specId",specialtyId);
        }

        List<VeZsRegistration> list = veZsRegistrationService.list(wrapper);

        String ids = "";
        for (VeZsRegistration veZsRegistration : list) {
            ids += veZsRegistration.getId() + ",";
        }

        //调用批量编制学号
        Result<?> result = batchCreateNum(ids);
        System.out.println(result);

        return Result.OK("按条件批量编制学号成功！");
    }

}
